package com.example.health_life.service;

import com.example.health_life.dao.Comment;
import com.example.health_life.dao.CommentRepository;
import com.example.health_life.dto.CommentDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Instant;
import java.util.List;

@Service
@Transactional
public class CommentServiceImpl implements CommentService{

    @Autowired
    private CommentRepository  commentRepository;

    @Override
    public Comment getCommentById(Integer id) {
        return commentRepository.findById(id).get();
    }

    @Override
    public List<Comment> getCommentList(Integer status) {
        if (status == 0) {
            return commentRepository.findAll();
        }
        return commentRepository.findByStatus((byte)status.intValue());
    }

    @Override
    public List<Comment> getCommentByUserId(Integer userId, Integer status) {
        if (status == 0) {
            return commentRepository.findByUserId(userId);
        }
        return commentRepository.findByUserIdAndStatus(userId, (byte)status.intValue());
    }

    @Override
    public List<Comment> getCommentByTypeId(Byte type, Integer typeId, Integer status) {
        if (status == 0) {
            return commentRepository.findByTypeAndTypeId(type, typeId);
        }
        return commentRepository.findByTypeAndTypeIdAndStatus(type, typeId, (byte)status.intValue());
    }

    @Override
    public Integer deleteComment(Integer id) {
        //查询评论是否存在
        Comment comment = commentRepository.findById(id).orElse(null);
        if(comment == null){
            return 0; // 或者抛出异常，例如 new EntityNotFoundException("Comment not found with id: " + id)
        }else{
            byte currentStatus = comment.getStatus();
            if(currentStatus == 1){
                comment.setStatus((byte) -1); // 标记为删除
            }else if(currentStatus == -1){
                comment.setStatus((byte) 1);  // 恢复为发布
            }
            commentRepository.save(comment); // 保存状态更改
            return comment.getId(); // 返回评论ID表示操作成功
        }
    }

    @Override
    public Integer addComment(CommentDTO commentDTO) {
        Comment comment = new Comment();
        comment.setUserId(commentDTO.getUserId());
        comment.setContent(commentDTO.getContent());
        comment.setType(commentDTO.getType());
        comment.setTypeId(commentDTO.getTypeId());
        
        // 设置默认值
        comment.setCreateTime(Instant.now());
        comment.setStatus((byte) 1);
        
        return commentRepository.save(comment).getId();
    }
}
